package com.itcast.aspect;

import com.itcast.mapper.LogMapper;
import com.itcast.mapper.UserMapper;
import com.itcast.pojo.Log;
import com.itcast.pojo.Result;
import com.itcast.pojo.User;
import com.itcast.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;


@Aspect
@Slf4j
@Component
public class LogInfoAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private UserMapper userMapper;

    @Around("execution(* com.itcast.controller.*.*(..))")
    public Result generateLog(ProceedingJoinPoint pjp) throws Throwable {
        log.info("进入aop切面方法");
        //获取操作方法
        String menthodName = pjp.getSignature().getName();
        //获取参数
        Object[] args = pjp.getArgs();
        String params = Arrays.toString(args);
        //开始时间
        long start = System.currentTimeMillis();
        Result result = (Result) pjp.proceed();
        long end = System.currentTimeMillis();
        //获取操作者id(登录操作从返回值中取)
        String token = request.getHeader("token");
        Integer userId;
        if (StringUtils.hasLength(token)) {
            userId = (Integer) JwtUtils.parseJWT(token).get("id");
        } else {
            userId = (Integer) JwtUtils.parseJWT(result.getData().toString()).get("id");
        }
        User user = userMapper.getById(userId);
        //执行时间
        Log logOperate = new Log(null, user.getUsername(), menthodName, params, (end - start), LocalDateTime.now());

        logMapper.insert(logOperate);
        log.info("aop切面执行完毕");
        return result;
    }
}
